<script setup lang="ts">
import { reactive, ref } from "vue";
import { onLoad, onPageScroll } from "@dcloudio/uni-app";
import { useAccountStore } from "@/stores/account";
import { postUserInfo, getUserDetail, postUserDetail } from '@/api/user'

const { userInfo, token } = useAccountStore();
const loading = ref(false);
const baseInfo = reactive(userInfo);
const profileDetail = reactive({
  realname: '',
  phone: '',
  company_name: '',
  position: '',
  email: '',
});

// 选选择上传图片
async function handleChooseImage() {
  // 选择图片
  uni.chooseImage({
    count: 1,
    sizeType: ['original'],
    success: ({tempFilePaths})=>{
      uni.showLoading({ title: '上传中' });
      // 上传
      uni.uploadFile({
        url: `https://api.minglvtang.com/api/upload/handler`, // post请求的地址
        filePath: tempFilePaths[0],
        name: 'file',
        header: {
          Authorization: token,
          Token: token
        },
        formData:{
          type:'avatar'
        },
        success: uploadFileRes => {
          // 这里要注意，uploadFileRes.data是个String类型，要转对象的话需要JSON.parse一下
          const { code, data, msg } = JSON.parse(uploadFileRes.data);
          // 错误提示
          if (code != 0) {
            uni.showToast({ title: msg, icon: 'none', duration: 3000 });
          } else {
            baseInfo.avatar = `https://api.minglvtang.com${data.url}`;
          }
        },
        fail: () => {
          //没有接口的情况模拟的失败状况跳转
          uni.showToast({ title: '文件上传失败', icon: 'error' });
        },
        complete: () => {
          uni.hideLoading();
        }
      });
    }
  });
}

async function handleSubmit(){
  const requiredFields = ['realname', 'phone', 'company_name', 'position'] as const;
  const hasEmptyField = requiredFields.some(field => !profileDetail[field]?.trim());
  if (hasEmptyField) {
    uni.showToast({ title: '请先填写剩余信息', icon: 'none' });
    return;
  }

  try{
    await postUserInfo(baseInfo);
    await postUserDetail(profileDetail);
    uni.showToast({ title: '保存成功' });
  } catch (error) {
    console.error('保存用户信息失败', error);
    uni.showToast({ title: '保存用户信息失败，请稍后重试', icon: 'none' });
  }
}

onLoad(async ()=>{
  const data = await getUserDetail();
  Object.assign(profileDetail, data);
});

// 吸顶变色
const isScrolled = ref(false);
onPageScroll((e)=>{
  isScrolled.value = e.scrollTop > 0;
});
</script>

<template>
<view class="relative overflow-hidden">
  <page-navbar title="我的资料" :hideTitle="true" :isScrolled="isScrolled"></page-navbar>

  <page-title title="我的资料"></page-title>

  <view class="mx-4 rounded-lg bg-white px-3 pb-3 mt-5">
    <view class="flex items-center justify-between border-b-(~ solid black/8) py-3">
      <view class="text-(sm #333333)">头像</view>
      <image class="size-10 rounded-full" :src="baseInfo.avatar || 'https://static.minglvtang.com/images/avatar_empty.jpeg'" mode="aspectFill" @click="handleChooseImage" />
    </view>
    <view class="flex items-center justify-between border-b-(~ solid black/8) py-3">
      <view class="text-(sm #333333)">昵称</view>
      <input class="text-(sm right)" v-model="baseInfo.nickname" placeholder="请输入昵称" />
    </view>
    <view class="flex items-center justify-between border-b-(~ solid black/8) py-3">
      <view class="text-(sm #333333)">真实姓名</view>
      <input class="text-(sm right)" v-model="profileDetail.realname" placeholder="填写真实姓名" />
    </view>
    <view class="flex items-center justify-between border-b-(~ solid black/8) py-3">
      <view class="text-(sm #333333)">手机号</view>
      <input class="text-(sm right)" v-model="profileDetail.phone" placeholder="填写手机号" />
    </view>
    <view class="flex items-center justify-between border-b-(~ solid black/8) py-3">
      <view class="text-(sm #333333)">邮箱地址</view>
      <input class="text-(sm right)" v-model="profileDetail.email" placeholder="填写邮箱地址" />
    </view>
  </view>

  <view class="mx-4 rounded-lg bg-white px-3 pb-3 mt-5">
    <view class="flex items-center justify-between border-b-(~ solid black/8) py-3">
      <view class="text-(sm #333333)">企业名称</view>
      <input class="text-(sm right)" v-model="profileDetail.company_name" placeholder="填写企业名称" />
    </view>
    <view class="flex items-center justify-between border-b-(~ solid black/8) py-3">
      <view class="text-(sm #333333)">职位</view>
      <input class="text-(sm right)" v-model="profileDetail.position" placeholder="填写职位" />
    </view>
  </view>

  <view class="mt-3 mx-4">
    <uv-button
      type="primary"
      size="large"
      text="保存"
      :custom-style="{
        fontSize: '18px',
        backgroundImage: 'linear-gradient(to right, #5199F9, #0164E6)',
        height: '48px',
        borderRadius: '8px',
        borderColor: 'transparent'
      }"
      :loading="loading"
      @click="handleSubmit"
    ></uv-button>
  </view>

</view>
</template>
